<template>
  <!-- 购物车列表 -->
  <table class="cart">
    <caption>
      全部商品
    </caption>
    <thead class="cart-th">
      <th class="cart-th1">选项</th>
      <th class="cart-th2">商品名称</th>
      <th class="cart-th3">配置</th>
      <th class="cart-th4">单价（元）</th>
      <th class="cart-th5">数量</th>
      <th class="cart-th6">总金额（元）</th>
      <th class="cart-th7">操作</th>
    </thead>
    <tbody class="cart-body">
      <tr class="cart-list" v-for="goods in cartInfoList" :key="goods.id">
        <td class="cart-list-con1">
          <input
            type="checkbox"
            name="chk_list"
            :checked="goods.isChecked"
            @change="changeChecked(goods.skuId, $event)"
          />
        </td>
        <td class="cart-list-con2">
          <router-link class="item-link" :to="`/goods/${goods.skuId}`">
            <img :src="goods.imgUrl" />
            <div class="item-msg">
              {{ goods.skuName }}
            </div>
          </router-link>
        </td>
        <td class="cart-list-con3">
          <div class="item-txt">语音升级款</div>
        </td>
        <td class="cart-list-con4">
          <span class="price">￥{{ goods.cartPrice }}</span>
        </td>
        <td class="cart-list-con5">
          <button
            class="mins"
            v-noRepeatClick
            @click="checkGoodsNum('reduce', -1, goods)"
          >
            -
          </button>
          <input
            autocomplete="off"
            type="number"
            :value="goods.skuNum"
            minnum="1"
            class="itxt"
            @change="checkGoodsNum('change', $event.target.value, goods)"
          />
          <button
            class="plus"
            v-noRepeatClick
            @click="checkGoodsNum('add', 1, goods)"
          >
            +
          </button>
        </td>
        <td class="cart-list-con6">
          <span class="sum"
            ><i class="iconfont icon-money">{{
              goods.skuNum * goods.cartPrice
            }}</i></span
          >
        </td>
        <td class="cart-list-con7">
          <button
            @click.prevent="delGoodsItem(goods.skuId)"
            class="btn btn-danger"
          >
            删 除
          </button>
          <button class="btn btn-edit">收 藏</button>
        </td>
      </tr>
    </tbody>
    <tfoot class="cart-tool">
      <td class="select-all">
        <input
          class="chooseAll"
          type="checkbox"
          :checked="allChecked"
          @change="changeAllChecked"
        />
        <span>全选</span>
      </td>
      <td class="option">
        <a
          @click.prevent="delAllChecked"
          :class="`${checkedNum <= 0 ? 'disabled' : ''}`"
          >删除选中的商品</a
        >
        <a :class="`${checkedNum <= 0 ? 'disabled' : ''}`">移到我的关注</a>
        <a class="disabled">清除下柜商品</a>
      </td>
      <td class="sumbtn">
        <div class="chosed">
          已选择 <span>{{ checkedNum }}</span> 件商品
        </div>
        <div class="sumprice">
          <em> 总价(不含运费)：</em
          ><i class="summoney iconfont icon-money">{{ totalPrice }}</i>
        </div>
        <a
          class="sum-btn"
          :class="`${checkedNum <= 0 ? 'disabled' : ''}`"
          @click.prevent="goTrade"
          >结 算</a
        >
      </td>
    </tfoot>
  </table>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "ShopCart",
  computed: {
    ...mapGetters("shopcart", ["cartInfoList"]),
    //选中商品的数量
    checkedNum() {
      if (this.cartInfoList) {
        return this.cartInfoList.reduce((pre, item) => pre + item.isChecked, 0);
      }
      return 0;
    },
    //是否全选
    allChecked() {
      if (this.cartInfoList) {
        return this.checkedNum == this.cartInfoList.length;
      }
      return false;
    },
    //总价格：所有选中商品的
    totalPrice() {
      //判断是cartInfoList是否有数据
      if (this.cartInfoList) {
        let totalPrice = 0; //存储商品总价格
        this.cartInfoList.forEach((item) => {
          if (item.isChecked == 1) {
            totalPrice += item.skuNum * item.cartPrice;
          }
        });
        return totalPrice || 0;
      }
      return 0;
    },
  },
  methods: {
    //获取购物车商品列表
    getShopCartList() {
      this.$store.dispatch("shopcart/getShopCartList");
    },
    //改变商品选中的状态选中或不选中
    async changeChecked(goodsId, e) {
      try {
        let isChecked = e.target.checked; //获取商品复选框状态
        const res = await this.$store.dispatch("shopcart/checkedGoods", {
          goodsId,
          isChecked,
        });
        if (res) this.getShopCartList(); //重新加载购物车商品列表
      } catch (error) {
        console.log(error);
      }
    },
    //所有商品全选或全不选
    async changeAllChecked(e) {
      try {
        const isChecked = e.target.checked; ////获取全选复选框状态
        const res = await this.$store.dispatch(
          "shopcart/changeAllChecked",
          isChecked
        );
        if (res) this.getShopCartList(); //重新加载购物车商品列表
      } catch (error) {
        console.log(error);
      }
    },
    //校验商品数量输入框重新改变事件
    async checkGoodsNum(type, num, goods) {
      let goodsNum = 0;
      switch (type) {
        case "add":
          goodsNum = num;
          break;
        case "reduce":
          if (goods.skuNum > 1) {
            goodsNum = num;
          } else {
            //调用删除商品函数
            return this.delGoodsItem(goods.skuId);
          }
          break;
        case "change":
          goodsNum = isNaN(num) || num < 1 ? 0 : parseInt(num) - goods.skuNum;
          break;
      }
      try {
        const res = await this.$store.dispatch("goods/addUpdateCars", {
          goodsId: goods.skuId,
          goodsNum,
        });
        if (res) this.getShopCartList();
      } catch (error) {
        console.log(error);
      }
    },
    //删除选中的商品
    delAllChecked() {
      //判断商品选中的数量是否大于等于1
      if (this.checkedNum >= 1) {
        try {
          //确认弹窗
          this.$confirm("确定要删除选中的所有商品吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              const res = await this.$store.dispatch("shopcart/delAllChecked");
              if (res) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                  center: true,
                });
                this.getShopCartList();
              }
            })
            .catch(() => {});
        } catch (error) {
          this.$message({
            type: "info",
            message: error,
            center: true,
          });
        }
      }
    },
    //删除商品选项
    delGoodsItem(goodsId) {
      try {
        this.$confirm("确定要删除该商品吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await this.$store.dispatch(
              "shopcart/deleteGoods",
              goodsId
            );
            if (res) {
              this.$message({
                type: "success",
                message: "删除成功!",
                center: true,
              });
              this.getShopCartList();
            }
          })
          .catch(() => {});
      } catch (error) {
        this.$message({
          type: "error",
          message: error,
          center: true,
        });
      }
    },
    //跳转到订单页面
    goTrade() {
      if (this.checkedNum >= 1) {
        this.$router.push({
          name: "Trade",
          params: { checkedNum: this.checkedNum },
        });
      }
    },
  },
  mounted() {
    //调用获取购物车商品列表
    this.getShopCartList();
  },
};
</script>

<style scoped lang="less">
.cart {
  width: 1200px;
  margin: 0 auto;
  caption {
    text-align: left;
    margin: 10px 0;
    font-size: 18px;
  }
  .cart-th {
    width: 100%;
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 10px;
    overflow: hidden;
    & > th {
      float: left;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-right: 1px solid #ddd;
    }
    .cart-th1 {
      width: 4%;
      input {
        vertical-align: middle;
      }
      span {
        vertical-align: middle;
      }
    }
    .cart-th2 {
      width: 30%;
    }
    .cart-th3,
    .cart-th4,
    .cart-th5,
    .cart-th6,
    .cart-th7 {
      width: 13%;
    }
  }
  .cart-body {
    border: 1px solid #ddd;
    text-align: center;
    .cart-list {
      padding: 10px;
      border-bottom: 1px solid #ddd;
      overflow: hidden;
      display: flex;
      align-items: center;
      & > td {
        float: left;
        text-align: center;
      }
      .cart-list-con1 {
        width: 4%;
        text-align: center;
      }
      .cart-list-con2 {
        width: 30%;
        .item-link {
          display: flex;
          flex-direction: row;
          text-align: left;
          img {
            width: 82px;
            height: 82px;
          }
          .item-msg {
            margin: 0 10px;
            line-height: 18px;
          }
        }
      }
      .cart-list-con3 {
        width: 13%;
        text-align: center;
      }
      .cart-list-con4 {
        width: 13%;
        text-align: center;
      }
      .cart-list-con5 {
        width: 13%;
        display: flex;
        align-items: center;
        justify-content: center;
        .mins {
          border: 1px solid #ddd;
          border-right: 0;
          color: #666;
          width: 30px;
          text-align: center;
          padding: 8px;
        }

        input {
          border: 1px solid #ddd;
          width: 50px;
          height: 33px;
          text-align: center;
          font-size: 16px;
        }
        .plus {
          border: 1px solid #ddd;
          border-left: 0;
          color: #666;
          width: 30px;
          text-align: center;
          padding: 8px;
        }
      }
      .cart-list-con6 {
        text-align: center;
        width: 13%;
        font-size: 16px;
      }
      .cart-list-con7 {
        text-align: center;
        width: 13%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        .btn {
          display: inline-block;
          padding: 4px 12px;
          margin-top: 8px;
          font-size: 14px;
          line-height: 20px;
          text-align: center;
          cursor: pointer;
          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
            0 1px 2px rgba(0, 0, 0, 0.05);
          border-radius: 4px;
        }

        .btn-danger {
          color: #fff;
          background-color: #da4f49;
          border: 1px solid #bd362f;
        }
        .btn-edit {
          color: #fff;
          background-color: blue;
          border: 1px solid blue;
        }

        .btn-danger:hover {
          color: #fff;
          background-color: #bd362f;
        }

        .btn:focus {
          outline: none;
        }
      }
    }
  }
  .cart-tool {
    width: 100%;
    overflow: hidden;
    border: 1px solid #ddd;
    display: flex;
    align-items: center;

    .select-all {
      width: 5%;
      padding: 10px;
      overflow: hidden;
      text-align: center;
      span {
        vertical-align: middle;
      }
      input {
        vertical-align: middle;
      }
    }
    .option {
      width: 30%;
      padding-left: 10px;
      overflow: hidden;
      display: flex;
      justify-content: center;
      flex-direction: row;
      a {
        flex: 3;
        font-size: 14px;
        cursor: pointer;
      }
      .disabled {
        color: rgb(211, 207, 207);
        cursor: not-allowed;
      }
    }

    .sumbtn {
      width: 65%;
      display: flex;
      align-items: center;
      justify-content: right;
      .chosed {
        span {
          font-weight: 600;
          color: red;
        }
      }
      .sumprice {
        padding: 0 20px;
        display: flex;
        align-items: center;
        .summoney {
          color: #c81623;
          font-size: 20px;
          font-weight: 600;
        }
      }
      a {
        display: block;
        position: relative;
        width: 96px;
        height: 52px;
        line-height: 52px;
        color: #fff;
        text-align: center;
        font-size: 20px;
        font-family: "Microsoft YaHei";
        background: #3498db;
        overflow: hidden;
      }
      .disabled {
        color: rgb(211, 207, 207);
        background-color: rgb(172, 171, 171);
        cursor: not-allowed;
      }
    }
  }
}
</style>